#!/usr/bin/bash
device="/dev/v4l/by-id/usb-Microsoft_Microsoft®_LifeCam_HD-3000-video-index0"
if ! [ -r $device ]; then
	echo "Please plug Microsoft Lifecam first"
	exit 1
fi

real_device=$( readlink -f $device)

function startNewKonsole() {
	konsole --profile "Transparent" -e "$0 $1"
	exit 0
}

originalArgs="$@"
while test "x$1" != "x"; do
	arg="$1"
	shift
	case $arg in
		"-h"|"--help")
		echo "Usage: $0 [-g]"
		echo -e "\t-g option launches guvcview to the proper device"
		exit 0
		;;
		"-g")
		guvcview -d $real_device 2>&1 >&/dev/null &
		;;
		"-k")
		startNewKonsole "$( echo $originalArgs | sed "s/-k//g")"
		;;
	esac
done

#allowed exposures: 5, 9 & 10 (same brightness), 19 & 20, 39, 78, 156, 312, 625, 1250, 2500,5000 and 10000
allowed_exposures="5 9 10 19 20 39 78 156 312 625 1250 2500 5000 10000"

function getCurrentExposure() {
	v4l2-ctl -d $device -C exposure_absolute | awk '{ print $2 }'
}

function setExposure() {
	v4l2-ctl -d $device -c exposure_auto=1
	v4l2-ctl -d $device -c exposure_absolute=$1
}

function increase() {
	current_exposure=$( getCurrentExposure )
	for i in $allowed_exposures; do
		if test $i -gt $current_exposure; then
			setExposure $i
			return
		fi 
	done
}

function decrease() {
	current_exposure=$( getCurrentExposure)
	previous_exposure=0
	for i in $allowed_exposures; do
		if test $i -eq $current_exposure; then
			setExposure $previous_exposure
			return
		fi
		previous_exposure=$i
	done
}

while read -n 1 -p "Enter action key: \"+\" or \"a\" to increase, \"-\" or \"z\" to decrease, \"q\" or ctrl+c to quit: " action; do
	case $action in
		"+"|"a")
		increase
		;;
		"-"|"z")
		decrease
		;;
		"q")
		exit 0
		;;
	esac
	echo " Current exposure: $( getCurrentExposure) "
	sleep 1
done
